package com.lab.book.getway.filter;

import com.alibaba.fastjson.JSON;
import com.lab.cloud.common.utils.JWTUtils;
import com.lab.cloud.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpCookie;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.CollectionUtils;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;


@Slf4j
@Component
public class AuthGlobalFilter implements GlobalFilter, Ordered {

    private static final List<String> SWAGGER_WHITE_LIST = Arrays.asList("/**/v2/api-docs", "/swagger-ui.html", "/swagger-resources/**", "/**/api-docs");
    private static final List<String> AUTH_WHITE_LIST = Arrays.asList("/auth/login", "/auth/refresh", "/auth/check");
    private static final List<String> WHITE_LIST = Stream.of(SWAGGER_WHITE_LIST, AUTH_WHITE_LIST).flatMap(Collection::stream).distinct().collect(Collectors.toList());

    private static final String JWT_TOKEN = HttpHeaders.AUTHORIZATION;
    private final AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        String path = request.getURI().getPath();

        log.info("url:{}", path);
        boolean action = false;
        for (String url : WHITE_LIST) {
            if (antPathMatcher.match(url, path)) {
                action = true;
                break;
            }
        }

        if (action) return chain.filter(exchange);

        String jwt = "";
        List<String> headers = request.getHeaders().get(JWT_TOKEN);
        if (!CollectionUtils.isEmpty(headers)) jwt = headers.get(0);

        if (StringUtils.isEmpty(jwt)) {
            MultiValueMap<String, HttpCookie> cookies = request.getCookies();
            if (!CollectionUtils.isEmpty(cookies)) {
                List<HttpCookie> cookie = cookies.get(JWT_TOKEN);
                if (!CollectionUtils.isEmpty(cookie)) jwt = cookie.get(0).getValue();
            }
        }

        if (StringUtils.isEmpty(jwt)) return out(response, JSON.toJSONString(R.error("未授权")));
        if (!JWTUtils.checkJWT(jwt)) return out(response, JSON.toJSONString(R.error("授权过期")));

        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }

    private Mono<Void> out(ServerHttpResponse response, String json) {
        response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        DataBuffer buffer = response.bufferFactory().wrap(json.getBytes(StandardCharsets.UTF_8));
        return response.writeWith(Mono.just(buffer));
    }
}
